#!/usr/bin/perl -w
# Update the /etc/hosts file with all hosts in this machine's network
# vim:tw=100 sw=2 expandtab ft=perl

# Available skip_steps items:
#       localhost - Add a localhost entry including the full host name
#       network - Add entries for every machine in the local network
#       hosts_append - Add custom hosts_append entries

if (i_should("localhost")) {
  my $domain = (flatten_list(c("$hostname/domain_name")))[0] || "localdomain";
  file_append(-file => "/etc/hosts",
              -add => "127.0.0.1\tlocalhost.localdomain localhost $hostname.$domain $hostname",
              -match => qr/(?:^127\.0\.0\.1\s.*|.+\s$hostname.*)/);
}

my @networks = flatten_list(c("$hostname/network"));
if (i_should("network") && @networks) {
  v "Looking for other machines in my networks (". join(" ", @networks). ")";

  foreach my $d (keys %m) {
    next if $d eq $hostname || $d =~ /^[A-Z]/;
    next unless my $ip = i_ip($d);

    my $in_my_network = 0;
    foreach my $n (@networks) {
      $in_my_network += grep { $_ eq $n } flatten_list(c("$d/network"));
    }
    next unless $in_my_network;

    my @hostnames = uniq(c("$d/full_hostname"), map({ "$d.$_" } c("$d/domain_name")), $d);
    next unless @hostnames;
    my $h = "$ip\t". join(" ", @hostnames);
    v "Adding $d:$ip to /etc/hosts (in $in_my_network network)";
    file_append(-file => "/etc/hosts", -add => $h, -match => qr/(?:^\Q$ip\E\s|\s\Q$d\E)/);
  }
}

if (i_should("hosts_append")) {
  my %append = flatten_hash(c("$hostname/hosts_append"));
  while (my($ip, $alias) = each %append) {
    v "Adding $ip $alias to /etc/hosts";
    file_append(-file => "/etc/hosts", -add => "$ip\t$alias",
                -match => qr/(?:^\b\Q$ip\E\b\s|\s\b\Q$alias\b\E)/);
  }
}
